#!/bin/bash

# 备份原配置文件
cp /etc/sysctl.conf /etc/sysctl.conf.bak.$(date +%F)

# 应用优化参数
cat >> /etc/sysctl.conf << EOF
# TIME_WAIT 优化 (防止端口耗尽)
net.ipv4.tcp_max_tw_buckets = 2000000
net.ipv4.tcp_tw_reuse = 1
net.ipv4.tcp_timestamps = 1

# 连接追踪优化
net.netfilter.nf_conntrack_max = 1048576
net.nf_conntrack_max = 1048576

# 端口范围扩展
net.ipv4.ip_local_port_range = 1024 65535

# 队列与缓冲优化
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65536
net.core.netdev_max_backlog = 32768

# FIN 超时优化
net.ipv4.tcp_fin_timeout = 30

# Keepalive 优化
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_keepalive_probes = 5
net.ipv4.tcp_keepalive_intvl = 15
EOF

# 立即生效配置
sysctl -p

echo "优化完成！建议重启系统使所有变更生效。"